package com.szgr.baoyin;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.activity.CalendarActivity;
import com.szgr.baoyin.activity.FirstInstallActivity;
import com.szgr.baoyin.model.CartProduct;
import com.szgr.baoyin.model.Product;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.FileUtils;
import com.szgr.baoyin.utils.JsonParser;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.SystemBarTintManager;
import com.szgr.baoyin.utils.ToastUtils;
import com.umeng.update.UmengUpdateAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class SplashActivity extends Activity implements View.OnClickListener {

    private Timer timer;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.REQUEST_SUCCESS:
                    MyApplication.getmInstance().setUserPhone(MyTool.getSP("username"));
                    MyApplication.getmInstance().setPassword(MyTool.getSP("password"));
                    MyApplication.getmInstance().setKey((String) msg.obj);
                    MyApplication.getmInstance().setIsLogin(true);
                    getCart();
                    break;
                case Constant.REQUEST_FAIL:
                    MyApplication.getmInstance().clearLoginMessage();
                    break;
                case 770:
                    MyApplication.getmInstance().setCartNum(0);
                    break;
                case 780:
                    MyApplication.getmInstance().setCartNum((int) msg.obj);
                    break;
            }
        }
    };
    private SystemBarTintManager mTintManager;
    private boolean isFirstInstall = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        String isFirst = MyTool.getSP("isFirstInstall");
        if("YES".equals(isFirst)){
            isFirstInstall = false;
        }

        //判断操作系统的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 状态栏透明 需要在创建SystemBarTintManager之前调用。
            setTranslucentStatus(true);//方法如下
        }
        mTintManager = new SystemBarTintManager(this);
        // 设置状态栏背景
        mTintManager.setStatusBarTintEnabled(true);
        mTintManager.setStatusBarTintResource(R.color.main_blue);//颜色可以随便修改

        //读取assets下城市lib数据返回json串
//        String cityStr = FileUtils.readAssetsFile(this, "citydata.json");
//        MyApplication.setAllCity(JsonParser.parseCityData(cityStr));
//        System.out.println("---城市---------> + " + MyApplication.getAllCity().size());

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                goToNextPage();
            }
        }, 1 * 1000);

        findViewById(R.id.splash_step_into).setOnClickListener(this);

        //只要退出程序就做一次自动登陆
        doLogin();

        getGoodsCategory();

//        getTest();
    }

    private void getTest() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_PROTECT_ADDRESS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---get test--->" + s);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void getGoodsCategory() {
        StringRequest sr = new StringRequest(Request.Method.GET, Constant.URL_GOODS_CATEGORY,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---get category--->" + s);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void doLogin() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_LOGIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            System.out.println("---login-->" + s);
                            if ("200".equals(code)) {
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                if (datas.has("error") || datas.has("errorcode")) {
//                                    ToastUtils.showToast(datas.getString("error"));
                                    mHandler.sendEmptyMessage(Constant.REQUEST_FAIL);
                                } else if (datas.has("key")) {
                                    String key = datas.getString("key");
                                    mHandler.obtainMessage(Constant.REQUEST_SUCCESS, key).sendToTarget();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            mHandler.sendEmptyMessage(Constant.REQUEST_FAIL);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mHandler.sendEmptyMessage(Constant.REQUEST_FAIL);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("username", MyTool.getSP("username"));
                map.put("password", MyTool.getSP("password"));
                map.put("client", "android");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.splash_step_into:
                timer.cancel();
                break;
        }
        goToNextPage();
    }

    private void goToNextPage() {
        if(!isFirstInstall) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }else{
            Intent intent = new Intent(this, FirstInstallActivity.class);
            startActivity(intent);
            finish();
        }
    }


    /**
     * 购物车
     */
    private void getCart() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_GET_CART,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---get cart-->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if("200".equals(code) && jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                if(datas.has("cart_list")){
                                    JSONArray cart_list = datas.getJSONArray("cart_list");
                                    Gson gson = new Gson();
                                    List<CartProduct> list = gson.fromJson(cart_list.toString(),new TypeToken<List<CartProduct>>(){}.getType());
                                    if(list.size() == 0){
                                        mHandler.obtainMessage(770).sendToTarget();
                                    }else{
                                        mHandler.obtainMessage(780,list.size()).sendToTarget();
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }



    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
}
